package com.longcai.piaojia.activity;

import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.longcai.piaojia.BaseApplication;
import com.longcai.piaojia.R;
import com.longcai.piaojia.adapter.ChooseCityListAdapter;
import com.longcai.piaojia.beans.CityNames;
import com.longcai.piaojia.dialog.WarnningDialog;
import com.longcai.piaojia.fragment.HomeFragment;
import com.longcai.piaojia.fragment.ShowFragment;
import com.longcai.piaojia.util.StringHelper;
import com.zcx.helper.bound.BoundView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;

/**
 * Created by Administrator on 2016/8/2.
 */
public class ChooseCityActivity extends BaseActivity {

    @BoundView(R.id.choose_city_current_city_tv) private TextView choose_city_current_city_tv;
    private HashMap<String, Integer> selector;// 存放含有索引字母的位置
    private LinearLayout layoutIndex;
    private ListView listView;
    private TextView tv_show;
    private ChooseCityListAdapter adapter;
    private String[] indexStr = {"#", "A", "B", "C", "D", "E", "F", "G", "H",
            "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
            "V", "W", "X", "Y", "Z"};
    private List<CityNames> cityNames = new ArrayList<>();
    private List<CityNames> newCityNames = new ArrayList<>();
    private int height;// 字体高度
    private boolean flag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_choose_city);

        setBackTrue();

        setTitleName(getString(R.string.choose_city_title_text));

        choose_city_current_city_tv.setText(BaseApplication.BasePreferences.getCityName());

        layoutIndex = (LinearLayout) this.findViewById(R.id.layout);
//        layoutIndex.setBackgroundColor(Color.parseColor("#00ffffff"));
        listView = (ListView) findViewById(R.id.listView);
        tv_show = (TextView) findViewById(R.id.tv);
        tv_show.setVisibility(View.GONE);

        setData();

        String[] allNames = sortIndex(cityNames);
        sortList(allNames);

        selector = new HashMap<String, Integer>();
        for (int j = 0; j < indexStr.length; j++) {// 循环字母表，找出newPersons中对应字母的位置
            for (int i = 0; i < newCityNames.size(); i++) {
                if (newCityNames.get(i).getName().equals(indexStr[j])) {
                    selector.put(indexStr[j], i);
                }
            }

        }
//        adapter = new ChooseCityListAdapter(this, newCityNames);
        adapter = new ChooseCityListAdapter(this, newCityNames);
        listView.setDivider(null);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                Log.v("maning", newCityNames.get(position).getRegion_id());

                new WarnningDialog(context, getResources().getString(R.string.choose_city_set_current_city_text) + getResources().getString(R.string.space) + newCityNames.get(position).getName().replaceAll(getString(R.string.choose_city_replace_text), "")) {
                    @Override
                    protected void onConfirm() {

                        String cityName = newCityNames.get(position).getName().replaceAll(getString(R.string.choose_city_replace_text), "");

//                        BaseApplication.BasePreferences.saveCityName(cityName);

                        if(cityName.length()>3){

                            cityName = cityName.substring(0,3) + "...";
                        }
                        Log.d(newCityNames.get(position).getRegion_id(),"heeeeeeeeeeeeeeeeeeeeeeeee");
                        Log.d(newCityNames.get(position).getRegion_id(),"heeeeeeeeeeeeeeeeeeeeeeeee");
                        BaseApplication.BasePreferences.saveCityId(newCityNames.get(position).getRegion_id());
                        BaseApplication.BasePreferences.saveCityName(cityName);
                        try {
                            ((HomeFragment.setCityNameIdCallback) getAppCallBack(HomeFragment.class)).setCityNameId(cityName, newCityNames.get(position).getRegion_id());

                            if(ShowFragment.is_live){

                                ((ShowFragment.setCityNameIdCallback) getAppCallBack(ShowFragment.class)).setCityNameId(cityName, newCityNames.get(position).getRegion_id());

                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        finish();

                    }
                }.show();


            }
        });

    }


    /**
     * 重新排序获得一个新的List集合
     *
     * @param allNames
     */
    private void sortList(String[] allNames) {
        for (int i = 0; i < allNames.length; i++) {
            if (allNames[i].length() != 1) {
                for (int j = 0; j < cityNames.size(); j++) {
                    if (allNames[i].equals(cityNames.get(j).getPinYinName())) {
                        CityNames p = new CityNames(cityNames.get(j).getName(), cityNames
                                .get(j).getPinYinName(), cityNames.get(j).getRegion_id());
                        newCityNames.add(p);
                    }
                }
            } else {
                newCityNames.add(new CityNames(allNames[i], ""));
            }
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        // 在oncreate里面执行下面的代码没反应，因为oncreate里面得到的getHeight=0
        if (!flag) {// 这里为什么要设置个flag进行标记，我这里不先告诉你们，请读者研究，因为这对你们以后的开发有好处
            height = layoutIndex.getMeasuredHeight() / indexStr.length;
            getIndexView();
            flag = true;
        }
    }

    /**
     * 获取排序后的新数据
     *
     * @param cityNames
     * @return
     */
    public String[] sortIndex(List<CityNames> cityNames) {
        TreeSet<String> set = new TreeSet<String>();
        // 获取初始化数据源中的首字母，添加到set中
        for (CityNames person : cityNames) {
            set.add(StringHelper.getPinYinHeadChar(person.getName()).substring(
                    0, 1));
        }
        // 新数组的长度为原数据加上set的大小
        String[] names = new String[cityNames.size() + set.size()];
        int i = 0;
        for (String string : set) {
            names[i] = string;
            i++;
        }
        String[] pinYinNames = new String[cityNames.size()];
        for (int j = 0; j < cityNames.size(); j++) {
            cityNames.get(j).setPinYinName(
                    StringHelper
                            .getPingYin(cityNames.get(j).getName().toString()));
            pinYinNames[j] = StringHelper.getPingYin(cityNames.get(j).getName()
                    .toString());
        }
        // 将原数据拷贝到新数据中
        System.arraycopy(pinYinNames, 0, names, set.size(), pinYinNames.length);
        // 自动按照首字母排序
        Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);
        return names;
    }

    /**
     * 绘制索引列表
     */
    public void getIndexView() {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, height);
        for (int i = 0; i < indexStr.length; i++) {
            final TextView tv = new TextView(this);
            tv.setLayoutParams(params);
            tv.setText(indexStr[i]);
            tv.setPadding(10, 0, 10, 0);
            layoutIndex.addView(tv);
            layoutIndex.setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event)

                {
                    float y = event.getY();
                    int index = (int) (y / height);
                    if (index > -1 && index < indexStr.length) {// 防止越界
                        String key = indexStr[index];
                        if (selector.containsKey(key)) {
                            int pos = selector.get(key);
                            if (listView.getHeaderViewsCount() > 0) {// 防止ListView有标题栏，本例中没有。
                                listView.setSelectionFromTop(
                                        pos + listView.getHeaderViewsCount(), 0);
                            } else {
                                listView.setSelectionFromTop(pos, 0);// 滑动到第一项
                            }
                            tv_show.setVisibility(View.VISIBLE);
                            tv_show.setText(indexStr[index]);
                        }
                    }
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
//                            layoutIndex.setBackgroundColor(Color
//                                    .parseColor("#606060"));
                            break;

                        case MotionEvent.ACTION_MOVE:

                            break;
                        case MotionEvent.ACTION_UP:
//                            layoutIndex.setBackgroundColor(Color
//                                    .parseColor("#00ffffff"));
                            tv_show.setVisibility(View.GONE);
                            break;
                    }
                    return true;
                }
            });
        }
    }

    private void setData() {

        AssetManager asset = context.getResources().getAssets();
        InputStream is;
        try {
            is = asset.open("region.txt");
            int size = is.available();// 取得数据流的数据大小
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            String txt = new String(buffer);

            try {
                JSONObject jsonObject = new JSONObject(txt);

                JSONArray jsonArray = jsonObject.optJSONArray("data");

                for(int i=0;i<jsonArray.length();i++){

                    JSONObject jsonObject_Province = jsonArray.optJSONObject(i);

                    JSONArray jsonArray_City = jsonObject_Province.optJSONArray("city");

                    for(int j=0;j<jsonArray_City.length();j++){

                        JSONObject jsonObject_City = jsonArray_City.optJSONObject(j);

                        CityNames city = new CityNames(jsonObject_City.optString("region_name"), jsonObject_City.optString("region_id"));

                        cityNames.add(city);
                      /*  if (jsonObject_City.optString("region_name").contains("哈尔滨")) {

                            CityNames city = new CityNames(jsonObject_City.optString("region_name"), jsonObject_City.optString("region_id"));

                            cityNames.add(city);

                        }*/

                    }

                }

            }catch (JSONException e){}

        } catch (IOException e) {}

    }

}
